import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link ,browserHistory} from 'react-router';
import request from 'superagent';
import api from '../api';
import {bind_change} from '../common/State';
import {  Modal,Icon,message,Table,Dropdown,Menu,Row,Col,Button,Input,InputNumber,Form ,Select,Switch} from 'antd';
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
const Option = Select.Option;
const InputGroup = Input.Group;
import Editor from '../common/Editor';
import moment from 'moment';

//导入常量
import {CHANNEL_TYPE} from '../constants/index';

class ChannelEdit extends React.Component {
  constructor(props, context){
      super(props, context);
      let {id} = props.location.query||{};
      this.state={
        channel:{
          id
        },
        employee:[]
      };
  }

  componentWillMount(){
    let {channel} = this.state;
    this.doFetch(channel.id);
  }

  componentDidMount(){
  
  }

  //通过ID查询
  async doFetch(id){
    let {result,employee} = await api('/generalize/channel/get',{id});
    if(result.cd!=0){
      message.error(result.msg);
      return
    }
    if(employee.cd != 0){
      message.error(employee.msg);
      return
    }
    this.setState({
      channel:result.data,
      employee:employee.data
    })
  }


  //保存事件
  btnSaveClick(event){
      const {validateFieldsAndScroll ,setFields} = this.props.form;
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          return
        }
        if(!/^1\d{10}$/g.test(values.phone)){
          setFields({
            phone:{
              value:values.phone,
              errors:[new Error('手机号格式不正确')]
            }
          })
          return;
        }
        this.save(values)
      })
  }
  //保存请求
  async save(values){
      let {channel} = this.state;
      values.status = channel.status;
      let params = Object.assign(channel,values);
      params.status = params.status==true?'1':'0';

      let result = await api('/generalize/channel/save',{channel});
      if(result.cd!=0){
        message.error(result.msg);
        return;
      }
      message.success('保存成功',1,() => {
        this.context.router.push(`/generalize/channel/list`)
      });

  }

  render() {
    const { getFieldDecorator} = this.props.form;
    let {channel,type,employee} = this.state;
    return (
        <div>
            <NavBar navs={[
              {title:`渠道管理`,href:`/generalize/channel/list`},
              {title:(channel.id?'编辑':'创建')+`渠道`}
            ]} />
            <ContentBody className='container'> 
                <h2>渠道基本信息</h2>
                <div className='height20'></div>
                <form>
                    <Row gutter={30}>
                      <Col span={12}>
                          <Form.Item 
                            label={`渠道类型`}
                          >
                            {getFieldDecorator('type', {
                              rules: [
                                {
                                  required: true,
                                  message: `请输入渠道类型`,
                                },
                              ],
                              initialValue:channel.type?(channel.type+""):""
                            })(
                                <Select 
                                    style={{width:'100%'}}
                                >
                                    <Option value=''>请选择</Option>
                                    {
                                        Object.keys(CHANNEL_TYPE).map((key,index) => {
                                            return (
                                                <Option value={key} key={index}>{CHANNEL_TYPE[key]}</Option>
                                            )
                                        })
                                    }
                                </Select>
                            )}
                          </Form.Item>
                      </Col >
                      <Col span={12}>
                          <Form.Item 
                            label={`渠道姓名`}
                          >
                            {getFieldDecorator('name', {
                              rules: [
                                {
                                  required: true,
                                  message: `请输入渠道姓名`,
                                },
                              ],
                              initialValue:channel.name||""
                            })(<Input
                                  placeholder={`请输入渠道姓名`}
                                />
                            )}
                          </Form.Item>
                      </Col >
                    </Row>
                    <Row gutter={30}>
                        <Col span={12}>
                          <Form.Item 
                            label={'渠道手机号'}
                          >
                            {getFieldDecorator('phone', {
                              rules: [
                                {
                                  required: true,
                                  message: `请输入渠道手机号`,
                                },
                              ],
                              initialValue:channel.phone||""
                            })(<InputNumber
                                  style={{width:'100%'}}
                                  placeholder={`请输入渠道手机号`}
                                />)}
                          </Form.Item>
                      </Col >
                      <Col span={12}>
                          <Form.Item 
                            label={'渠道机构'}
                          >
                            {getFieldDecorator('organization', {
                              rules: [
                                {
                                  required: false,
                                  message: `请输入渠道机构`,
                                },
                              ],
                              initialValue:channel.organization||""
                            })(<Input
                                  placeholder={`请输入渠道机构`}
                                />)}
                          </Form.Item>
                      </Col >
                    </Row>
                    <Row gutter={30}>
                        <Col span={12}>
                          <Form.Item 
                            label={'渠道归属'}
                          >
                            {getFieldDecorator('link_employee', {
                              rules: [
                                {
                                  required: true,
                                  message: `请输入渠道归属`,
                                },
                              ],
                              initialValue:channel.link_employee?channel.link_employee.toString():""
                            })(
                              <Select
                                style={{width:'100%'}}
                              >
                                <Option value=''>请选择</Option>
                                {employee.map((item,index) => {
                                  return (
                                    <Option key={index} value={item.id.toString()}>{item.name}</Option>
                                  )
                                })}
                              </Select>
                            )}
                          </Form.Item>
                      </Col >
                    </Row>
                    {/* <div className='height30'></div>
                    <h2>渠道状态设置</h2>
                    <div className='height10'></div>
                    <Row gutter={30}>
                      <Col span={12}>
                        <label >是否开启:</label>
                        <Switch 
                          checkedChildren={'开'} 
                          unCheckedChildren={'关'}
                          checked={channel.status==1?true:false} 
                          onChange={(checked)=>{
                            channel.status = checked;
                            this.setState({channel});
                          }}
                        />
                      </Col >
                      
                    </Row> */}
                </form>
               
                <div className="text-center ">
                    <Button  
                      type='primary'
                      onClick={this.btnSaveClick.bind(this)}
                    >
                      保存
                    </Button>
                    <Button  
                      type='default'
                      style={{marginLeft:"20px"}} 
                      onClick={()=>{this.context.router.push(`/generalize/channel/list`)}}
                    >
                      返回
                    </Button>
                 </div>
            </ContentBody>
            
        </div>
    );
  }
}
ChannelEdit.contextTypes= { router: React.PropTypes.object.isRequired};

export default Form.create()(ChannelEdit);
